package com.novabluetooth.services.bluetooth2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.nova.NovaGlobalConts;
import com.novabluetooth.views.SBCLActivity;

import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
 * 和泰达耳温枪2.0
 * @author nova
 *
 */
public class HTDEWQ2Thread extends Thread {

	private static final String TAG = "HTDEWQ2Thread";
	private BluetoothSocket btSocket;
	private Handler btHandler;
	private InputStream btInStream;
	private OutputStream btOutStream;
	int mCount = 0;

	String out = "5E4854444C696E6B0D";
	String shut = "5E4854444F66660D";

	public HTDEWQ2Thread(BluetoothSocket bluetoothSocket, Handler mHandler) {

		// TODO Auto-generated constructor stub
		Log.e("LeeTag", "TFThread");
		this.btSocket = bluetoothSocket;
		this.btHandler = mHandler;
		InputStream tmpIn = null;
		OutputStream tmpOut = null;
		try {
			tmpIn = bluetoothSocket.getInputStream();
			tmpOut = bluetoothSocket.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		btInStream = tmpIn;
		btOutStream = tmpOut;
	}

	@Override
	public void run() {

		Log.e("LeeTag", "TFThread run...");
		if ((btInStream != null) && (btOutStream != null)) {
			boolean isRun = true;
			byte[] buffer = new byte[1024];
			int readSize = 0;

			String getData = null;
			try {
				Log.e("LeeTag", "Write Request Data");
				write(String2Byte(out));

				Thread.sleep(2000);

				readSize = btInStream.read(buffer);
				System.out.println("获得数据Byte数组的大小为：" + readSize);
				Bundle bundle = new Bundle();
				if (readSize <= 0) {
					Log.e("Tag", "readSize《=0");
					bundle.putString(SBCLActivity.EW_ERRORMSG, "测量数据不正确");
				}

				if (readSize < 8) {
					Log.e("Tag", "readSize《=0");
					bundle.putString(SBCLActivity.EW_ERRORMSG, "测量数据不正确");
				}

				if (btHandler != null) {
					mCount = 0;
					Log.e("Tag", "readSize大于0");

					getData = byteArray2HexString(buffer, readSize);
					Log.e(TAG, "获取到的数据为：  " + getData);

					write(String2Byte(shut));

					
					String address = btSocket.getRemoteDevice().getAddress();
//					bundle.putString(SBCLActivity.EW, address);

					Thread.sleep(1000);
					btInStream.close();
					btOutStream.close();
					btInStream = null;
					btOutStream = null;
					cancel();
					// FF 00 00 00 01 01 71 8E
					// 5E3030303033362E37430D
					String tf = toStringHex(getData.substring(10, 18));
					// int tf = Integer.parseInt(getDate.substring(10, 18), 16);
					
					if(NovaGlobalConts.isFloatNumberMatcher(tf)){
						Log.e(TAG, "获取最终结果:"+tf);
						float bg = Float.parseFloat(tf);
						bundle.putFloat(SBCLActivity.EW, bg);
					}else{
						bundle.putString(SBCLActivity.EW_ERRORMSG, "测量数据不正确");
					}
					
					Message msg = new Message();
					msg.setData(bundle);
					msg.what = MessageValue.MSG_READ_TF;
					btHandler.sendMessage(msg);
					return;
				}
				Log.i("LeeTag", "结束");

			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void cancel() {
		if (btSocket != null) {
			try {
				// Thread.sleep(2000);
				btSocket.close();
				btSocket = null;
				Log.e("Tag", "关闭Socket");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static byte[] String2Byte(String hexString) {
		if (hexString.length() % 2 == 1)
			return null;
		byte[] ret = new byte[hexString.length() / 2];
		for (int i = 0; i < hexString.length(); i += 2) {
			ret[i / 2] = Integer.decode("0x" + hexString.substring(i, i + 2)).byteValue();
		}
		return ret;
	}

	public static String byteArray2HexString(byte[] bytes, int byteSize) {
		byte[] buf = bytes;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteSize; i++) {
			String str = Integer.toHexString(buf[i] & 0xFF);
			if (str.length() < 2) {
				str = '0' + str;
			}
			str = str.toUpperCase();
			sb.append(str);
		}
		return sb.toString();
	}

	// 转化十六进制编码为字符串
	public static String toStringHex(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	private void write(byte[] bytes) {
		try {
			Log.i("Tag", "发送指令");
			btOutStream.write(bytes);
			btOutStream.flush();
		} catch (IOException e) {
			Log.e("tag", "出错了");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
